package cn.jhc.bookstore.listener;

import cn.jhc.bookstore.Constants;
import cn.jhc.bookstore.cn.jhc.bookstore.db.BookDao;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.annotation.WebListener;
import org.apache.commons.dbutils.QueryRunner;
import org.h2.jdbcx.JdbcDataSource;

@WebListener
public class BookStoreContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        JdbcDataSource jdbcDataSource = new JdbcDataSource();
        jdbcDataSource.setURL("jdbc:h2:file:~/bookstore.db;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
        jdbcDataSource.setUser("sa");
        QueryRunner queryRunner = new QueryRunner(jdbcDataSource);
        sce.getServletContext().setAttribute(Constants.QUERY_RUNNER, queryRunner);
        BookDao.createTable(queryRunner);
        BookDao.insertExampleData(queryRunner);
    }
}
